<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>使用Promise和XHR获取省份</title>
</head>

<body>
    <p></p>
    <script>
        const promise = new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest()
            xhr.open('GET', 'http://hmajax.itheima.net/api/province')
            // 请求发送完成后触发事件
            xhr.addEventListener('loadend', () => {
                if (xhr.status >= 200 & xhr.status < 300) {
                    resolve(JSON.parse(xhr.response))
                }else{
                    reject(new Error(xhr.response))
                }
            })
            // 发送请求
            xhr.send()
        })

        // 关联成功和失败函数
        promise.then((result) => {
            // 对响应结果做后续处理
            document.querySelector('p').innerHTML = result.list.join('<br>')
        }).catch(error => {
            document.querySelector('p').innerHTML = error.message
        })
    </script>
</body>

</html>